package com.example.snakefinal;

import android.content.Context;
import android.graphics.Point;

import java.util.Random;

public class RobotSnake extends Snake implements Runnable {
    public RobotSnake(Context context, Point mr, int SkinResource) {
        super(context, mr, SkinResource);
    }

    private SnakeGame snakeGame;

    public void setSnakeGame(SnakeGame snakeGame) {
        this.snakeGame = snakeGame;
    }

    @Override
    public void run() {
        while (true) {
            if (getSegmentLocations().isEmpty()) {
                // 未开始，无需进行
                continue;
            }
            // 布置正在游戏不开始
            if (snakeGame.CURRENT_STATE != GAME_STATE.PLAYING_SCREEN) {
                continue;
            }
            // 获取地图和食物列表
            Point headPoint = getSegmentLocations().get(0);
            // 临近墙体就转向
            if (headPoint.x <= 50
                    || headPoint.x > Const.MAP_W - 50
                    || headPoint.y <= 50
                    || headPoint.y > Const.MAP_H - 50) {
                Random random = new Random();
                Heading value = Heading.values()[random.nextInt(4)];
                if (value != getHeading()) {
                    switchHeading(value);
                }
                continue;
            }
            // 寻找离自己最近的食物
            Food targetFood = snakeGame.getTargetFood(this);
            if (targetFood == null) {
                continue;
            }
            // 切换蛇头至目标
            Point location = targetFood.getLocation();
            if (Math.abs(location.x - headPoint.x) > Math.abs(location.y - headPoint.y)) {
                if (location.x < headPoint.x + 10) {
                    switchHeading(Heading.LEFT);
                } else if (location.x > headPoint.x - 10) {
                    switchHeading(Heading.RIGHT);
                }
            } else {
                if (location.y < headPoint.y + 10) {
                    switchHeading(Heading.UP);
                } else if (location.y > headPoint.y - 10) {
                    switchHeading(Heading.DOWN);
                }
            }


        }
    }

    @Override
    void reset() {
        super.reset();
        getSegmentLocations().get(0).x = new Random().nextInt(screenSize.x - 400) + 200;
        getSegmentLocations().get(0).y = new Random().nextInt(screenSize.y - 400) + 200;
        switchHeading(Heading.values()[new Random().nextInt(4)]);
    }
}
